"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { getRankings, getRankingDetail } from "@/lib/api-client"
import type { Ranking } from "@/types/ranking"
import { Skeleton } from "@/components/ui/skeleton"
import type { Song } from "@/types"
import { ChevronRight, ChevronLeft } from "lucide-react"
import { Button } from "@/components/ui/button"

// 默认背景颜色，当后端没有返回时使用
const DEFAULT_COLORS = ["bg-[#e13e74]", "bg-[#e13e74]", "bg-[#5c9bbe]", "bg-[#5cbea7]", "bg-[#5c9bbe]"]

export function RankingPreview() {
  const [rankings, setRankings] = useState<Ranking[]>([])
  const [rankingSongs, setRankingSongs] = useState<Record<string, Song[]>>({})
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [currentPage, setCurrentPage] = useState(0)
  const [totalPages, setTotalPages] = useState(0)
  const itemsPerPage = 3 // 每页显示3个排行榜

  useEffect(() => {
    async function fetchRankings() {
      try {
        setLoading(true)
        const response = await getRankings()

        if (response.success && response.data) {
          setRankings(response.data)
          setTotalPages(Math.ceil(response.data.length / itemsPerPage))

          // 获取当前页的排行榜的前3首歌曲
          const currentRankings = response.data.slice(currentPage * itemsPerPage, (currentPage + 1) * itemsPerPage)

          const songsData: Record<string, Song[]> = {}

          await Promise.all(
              currentRankings.map(async (ranking) => {
                try {
                  const detailResponse = await getRankingDetail(ranking.id)
                  if (detailResponse.success && detailResponse.data) {
                    // 只保存前3首歌曲
                    songsData[ranking.id] = detailResponse.data.slice(0, 3)
                  }
                } catch (err) {
                  console.error(`获取排行榜 ${ranking.name} 详情失败:`, err)
                }
              }),
          )

          setRankingSongs(songsData)
        } else {
          setError("获取排行榜失败")
        }
      } catch (err) {
        setError("获取排行榜失败")
        console.error(err)
      } finally {
        setLoading(false)
      }
    }

    fetchRankings()
  }, [currentPage])

  const handlePrevPage = () => {
    if (currentPage > 0) {
      setCurrentPage(currentPage - 1)
    }
  }

  const handleNextPage = () => {
    if (currentPage < totalPages - 1) {
      setCurrentPage(currentPage + 1)
    }
  }

  if (loading) {
    return (
        <div>
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-2xl font-bold">排行榜</h2>
            <div className="flex items-center gap-2">
              <Skeleton className="h-8 w-8 rounded-full" />
              <Skeleton className="h-8 w-8 rounded-full" />
              <Skeleton className="h-5 w-16" />
            </div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-4">
            {Array.from({ length: 3 }).map((_, i) => (
                <Skeleton key={i} className="h-[240px] rounded-lg" />
            ))}
          </div>
        </div>
    )
  }

  if (error) {
    return <div className="text-red-500">{error}</div>
  }

  // 获取当前页的排行榜
  const currentRankings = rankings.slice(currentPage * itemsPerPage, (currentPage + 1) * itemsPerPage)

  return (
      <div>
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-2xl font-bold">排行榜</h2>
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-2">
              <Button
                  variant="ghost"
                  size="icon"
                  onClick={handlePrevPage}
                  disabled={currentPage === 0}
                  className="h-8 w-8 rounded-full"
              >
                <ChevronLeft className="h-4 w-4" />
                <span className="sr-only">上一页</span>
              </Button>
              <div className="flex items-center justify-center h-2">
                {Array.from({ length: totalPages }).map((_, i) => (
                    <div
                        key={i}
                        className={`h-2 w-2 rounded-full mx-1 ${i === currentPage ? "bg-primary" : "bg-gray-300"}`}
                    />
                ))}
              </div>
              <Button
                  variant="ghost"
                  size="icon"
                  onClick={handleNextPage}
                  disabled={currentPage === totalPages - 1}
                  className="h-8 w-8 rounded-full"
              >
                <ChevronRight className="h-4 w-4" />
                <span className="sr-only">下一页</span>
              </Button>
            </div>
            <Link href="/rank" className="text-sm text-muted-foreground flex items-center hover:text-primary">
              更多 <ChevronRight className="h-4 w-4" />
            </Link>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-4">
          {currentRankings.map((ranking, index) => {
            const songs = rankingSongs[ranking.id] || []
            // 使用后端返回的背景颜色，如果没有则使用默认颜色
            const bgColor = ranking.backgroundColor
                ? `bg-[${ranking.backgroundColor}]`
                : DEFAULT_COLORS[index % DEFAULT_COLORS.length]

            return (
                <Link
                    key={ranking.id}
                    href={`/rank/${ranking.id}`}
                    className={`${bgColor} rounded-lg p-4 text-white relative group cursor-pointer min-h-[240px] flex flex-col hover:shadow-lg transition-shadow`}
                >
                  <div className="mb-6">
                    <div className="text-lg font-bold opacity-80">巅峰榜</div>
                    <div className="text-xl font-bold mb-4">{ranking.name.replace("榜", "")}</div>
                  </div>

                  <ul className="space-y-3 flex-1">
                    {songs.length > 0 ? (
                        songs.map((song, index) => (
                            <li key={song.id} className="text-sm">
                              <div className="flex items-baseline gap-2">
                                <span className="font-bold">{index + 1}</span>
                                <div className="flex-1 min-w-0">
                                  <div className="truncate">{song.title}</div>
                                  <div className="truncate opacity-80 text-xs">{song.artists}</div>
                                </div>
                              </div>
                            </li>
                        ))
                    ) : (
                        <li className="text-sm opacity-80">加载中...</li>
                    )}
                  </ul>
                </Link>
            )
          })}
        </div>
      </div>
  )
}

